package org.fastsyncer.manager.log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.DefaultThreadFactory;
import org.fastsyncer.common.constant.MappingConstant;
import org.fastsyncer.common.util.UUIDUtil;
import org.fastsyncer.manager.framework.AbstractDirectory;
import org.fastsyncer.manager.util.FileUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class LogFactory extends AbstractDirectory {

    private static final Logger logger = LoggerFactory.getLogger(LogFactory.class);

    private static volatile LogFactory instance = null;

    public static LogFactory getInstance() {
        if (null == instance) {
            synchronized (LogFactory.class) {
                if (null == instance) {
                    instance = new LogFactory();
                }
            }
        }
        return instance;
    }

    // 存放日志任务,默认1000个上限
    private final BlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>(1000);

    // 定义任务处理线程池,当第执行二个任务时,第一个任务完成,会复用线程,不会新建线程,执行结束一段时间会自动回收
    private final ExecutorService pool = Executors.newCachedThreadPool(new DefaultThreadFactory("Log-threadpool"));

    // 驱动日志读写管道
    private volatile Map<String, Pipeline> router = new ConcurrentHashMap<>();

    /**
     * 记录同步日志
     * 
     * @param msg 日志
     * <ol>
     *  <li>
     *      <p>同步格式：</p>
     *      <pre>
     *      {
     *          "id":"e2dd5c03e512495a9a9e7e958bdd9464",
     *          "success":0,
     *          "fail":2,
     *          "reason":[
     *              {"params":{xxx},"message":"xxx"},
     *              {"params":{xxx},"message":"xxx"}
     *          ]
     *      }
     *      </pre>
     *  </li>
     *  <li>
     *      <p>迁移格式：</p>
     *      <pre>
     *      {
     *          "id":"e2dd5c03e512495a9a9e7e958bdd9464",
     *          "success":0,
     *          "fail":2,
     *          "reason":[
     *              {"message":"xxx"},
     *              {"message":"xxx"}
     *          ]
     *      }
     *      </pre>
     *  </li>
     *  <li>
     *      <p>删除格式：</p>
     *      <pre>
     *      {
     *          "id":"e2dd5c03e512495a9a9e7e958bdd9464",
     *          "del": [
     *              {
     *                  "i":0,
     *                  "id":e2dd5c03e512495a9a9e7e958bdd9464_7cde28d343bc4dd58f1a6ea9f280d1c9
     *              },
     *              {xxx}, ...
     *          ]
     *      }
     *      </pre>
     *  </li>
     * </ol>
     */
    public void handle(JSONObject msg) {
        if (queue.isEmpty()) {
            queue.offer(msg);
            // 触发日志写入线程
            pool.execute(() -> {
                groupAndMerge();
            });
        } else {
            queue.offer(msg);
        }
    }

    public File getLog(String key) {
        try {
            StringBuilder logPath = new StringBuilder();
            // 例如D:\fastsyncer\8ac99237e022477b9aeaa84da421c1e2
            logPath.append(storePath).append(File.separatorChar).append(key);
            // 检查文件夹
            FileUtil.createDirIfNotExist(logPath.toString());

            // 例如D:\fastsyncer\8ac99237e022477b9aeaa84da421c1e2\8ac99237e022477b9aeaa84da421c1e2.data
            logPath.append(File.separatorChar).append(key).append(MappingConstant.STORE_LOG_SUFFIX);
            String logAbsPath = logPath.toString();
            FileUtil.createFileIfNotExist(logAbsPath);
            return new File(logAbsPath);
        } catch (Exception e) {
            logger.error("Get failed:%s", e.getMessage());
        }
        return null;
    }

    public boolean writeLog(String key, Object value, boolean append) {
        try {
            StringBuilder logPath = new StringBuilder();
            // 例如D:\fastsyncer\8ac99237e022477b9aeaa84da421c1e2
            logPath.append(storePath).append(File.separatorChar).append(key);
            // 检查文件夹
            FileUtil.createDirIfNotExist(logPath.toString());

            // 例如D:\fastsyncer\8ac99237e022477b9aeaa84da421c1e2\8ac99237e022477b9aeaa84da421c1e2.txt
            String logAbsPath = logPath.append(File.separatorChar).append(key).append(MappingConstant.STORE_LOG_SUFFIX).toString();
            FileUtil.createFileIfNotExist(logAbsPath);
            // true:追加,false:覆盖
            FileUtil.write(logAbsPath, value.toString(), append);
            return true;
        } catch (Exception e) {
            logger.error("Write failed:%s", e.getMessage());
        }
        return false;
    }

    public boolean deleteLog(String key) {
        // 例如D:\fastsyncer\8ac99237e022477b9aeaa84da421c1e2\8ac99237e022477b9aeaa84da421c1e2.txt
        String logPath = new StringBuilder(storePath).append(File.separatorChar).append(key).append(File.separatorChar).append(key).append(MappingConstant.STORE_LOG_SUFFIX)
                .toString();
        File file = new File(logPath);
        boolean exists = file.exists();
        if (exists) {
            file.delete();
        }
        return exists;
    }

    public void deleteLog(String key, List<Row> delLog) {
        if(StringUtils.isBlank(key) || null == delLog || delLog.isEmpty()){
            return;
        }
        // 例如D:\fastsyncer\8ac99237e022477b9aeaa84da421c1e2\8ac99237e022477b9aeaa84da421c1e2.txt
        StringBuilder logPath = new StringBuilder(storePath).append(File.separatorChar).append(key).append(File.separatorChar).append(key).append(MappingConstant.STORE_LOG_SUFFIX);
        File dest = new File(logPath.toString());
        if (!dest.exists()) {
            return;
        }
        FileReader reader = null;
        BufferedReader br = null;
        OutputStream os = null;
        OutputStreamWriter bw = null;
        File newTmp = null;
        Map<Integer, Integer> rel = null;
        try {
            reader = new FileReader(dest);
            br = new BufferedReader(reader);
            newTmp = new File(logPath.append(".tmp").toString());
            os = new FileOutputStream(newTmp);
            bw = new OutputStreamWriter(os);
            String str = null;
            int i = -1;
            rel = convertToIndex(delLog);
            Integer d = null;
            while ((str = br.readLine()) != null) {
                i++;
                d = rel.get(i);
                if(null != d){
                    rel.remove(d);
                    continue;
                }
                bw.write(str.concat("\n"));
            }
            bw.flush();
        } catch (Exception e) {
            logger.error("Delete log error:%s", e.getLocalizedMessage());
        } finally {
            close(bw, os, br, reader);
            rel = null;
            delLog.clear();
        }
        // 删除旧文件
        FileUtil.delete(dest);
        // 重命名新文件为旧文件
        FileUtil.renameTo(newTmp, dest);
    }

    public void removePipeline(String key) {
        synchronized (router) {
            router.remove(key);
        }
    }

    private Map<Integer, Integer> convertToIndex(List<Row> delLog) {
        int size = delLog.size();
        Map<Integer, Integer> res = new HashMap<>(size);
        for (int i = 0; i < size; i++) {
            // <删除的文本行数, delLog下标>
            res.put(delLog.get(i).getIndex(), i);
        }
        return res;
    }
    
    private void groupAndMerge() {
        // 1.将所有的消息分类,放入Pipeline缓存队列
        try {
            JSONObject handle = null;
            while (!queue.isEmpty()) {
                handle = queue.poll();
                String id = handle.getString("id");
                // 判断日志类型（新增,删除）
                if (!handle.isNull("del")) {
                    delete(id, handle.getJSONArray("del"));
                } else {
                    write(id, handle.getJSONArray("reason"));
                }
            }
        } catch (Exception e) {
            logger.error("Persistent storage error log failed:%s", e.getLocalizedMessage());
        }
        // 2.通知所有的管道,执行批量写入操作
        if (null != router && !router.isEmpty()) {
            for (Entry<String, Pipeline> obj : router.entrySet()) {
                obj.getValue().flush();
            }
        }
    }

    private void delete(String id, JSONArray arr) throws JSONException {
        int errSize = arr.length();
        if (errSize > 0) {
            JSONObject row = null;
            Row r = null;
            for (int i = 0; i < errSize; i++) {
                row = arr.getJSONObject(i);
                r = new Row(row.getInt("i"), row.getString("id"));
                this.getPipeline(id).delLog(r);
            }
        }
    }

    private void write(String id, JSONArray arr) throws JSONException {
        int errSize = arr.length();
        if (errSize > 0) {
            StringBuilder row = new StringBuilder();
            JSONObject obj = null;
            String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            for (int i = 0; i < errSize; i++) {
                obj = arr.getJSONObject(i);
                obj.put("id", id.concat("_").concat(UUIDUtil.getUUID()));
                obj.put("date", date);
                row.append(obj).append("\n");
            }
            this.getPipeline(id).writeLog(row);
        }
    }
    
    public void close(OutputStreamWriter bw, OutputStream os, BufferedReader br, FileReader reader){
        if (null != bw) {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != os) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        close(br, reader);
    }
    
    public void close(BufferedReader br, FileReader reader){
        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public Pipeline getPipeline(String id) {
        Pipeline pip = router.get(id);
        if (null == pip) {
            synchronized (router) {
                pip = router.get(id);
                if (null == pip) {
                    router.put(id, new Pipeline(this, id));
                    pip = router.get(id);
                }
            }
        }
        return pip;
    }

}
